package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.common.support.utils.FstObjectSerializeUtil;
import com.sanerzone.smscenter.biz.entity.MessageTopic;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.GatewayStartUp;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 云之讯纯真
 * 支持批量发送，支持多号码，号码之间用英文逗号隔开，最多100个
 */
public class SmsApiYZXCZv1 extends GateWayHttpAbstract
{

    public SmsApiYZXCZv1(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        HashMap<String,String> header = Maps.newHashMap();
        header.put("Accept","application/json");
        header.put("Content-Type","application/json;charset=utf-8");

        Map<String,Object> params = Maps.newHashMap();
        params.put("clientid",paramsMaps.get("clientid"));
        params.put("password", DigestUtils.md5Hex(paramsMaps.get("password")));
        params.put("mobile",mt.getPhone());
        params.put("smstype",paramsMaps.get("smstype"));//短信类型，0：通知短信，4：验证码短信，5：营销短信

        String content = "";
        try{
//            content = URLEncoder.encode(mt.getSmsContent(),"utf-8");
            content = new String(mt.getSmsContent().getBytes(),"utf-8");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            logger.error("网关:{},手机：{},内容：{}，内容编码错误。", this.gateWayID, mt.getPhone(), mt.getSmsContent());
        }
        params.put("content",content);
        params.put("uid",mt.getId());
        String url = paramsMaps.get("apiUrl") + "/sms-partner/access/" + paramsMaps.get("account") + "/sendsms";
        String result =  HttpRequest.sendPostJson(url, JSON.toJSONString(params), header, 2000);
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);

        List<SMSSRMessage> resultList = Lists.newArrayList();
        SMSSRMessage message = initGatewayResultMessage(result, mt, "code");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        JSONObject object = JSON.parseObject(result);
        if(StringUtils.equals(message.getResult(), "F10199")) {
            JSONArray array = JSON.parseArray(object.getString("data"));
            taskid = mt.getId();
            for(int i=0 ; i < array.size() ;i++){
                JSONObject data = array.getJSONObject(i);
                resultCode = data.getString("code");
                resultMessage = data.getString("msg");
                message.setMsgkey(data.getString("sid"));
                setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
                resultList.add(message);
            }
        }
        return resultList;
    }

    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        Map<String,String> map = Maps.newHashMap();
        map.put("code", "0");
        map.put("code", "success");
        if (StringUtils.isNotBlank(text)) {
            JSONArray result = JSON.parseArray(text);
            for(int i=0 ; i < result.size() ;i++){
                JSONObject data = result.getJSONObject(i);
                SMSRTMessage smsRtMessage = initSmsRtMessage(data.getString("uid"), data.getString("sid"),data.getString("mobile"),
                        data.getString("report_status"), "SUCCESS");
                rtList.add(smsRtMessage);
            }
        } else {
            map.put("code", "-1");
            map.put("code", "error");
        }
        return new SmsHttpMsgResponse(JSON.toJSONString(map));
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        Map<String,String> map = Maps.newHashMap();
        map.put("code", "0");
        map.put("code", "success");
        if (StringUtils.isNotBlank(text)) {
            JSONObject data = JSON.parseObject(text);
            SMSMOMessage sMSMOMessage = new SMSMOMessage();
            sMSMOMessage.setGateWayID(gateWayID);
            String conetent = data.getString("content");
            try {
                conetent = URLDecoder.decode(data.getString("content"),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sMSMOMessage.setMsgContent(conetent);
            sMSMOMessage.setMsgid(data.getString("moid"));
            sMSMOMessage.setPhone(data.getString("mobile"));
            sMSMOMessage.setSenttime(data.getString("reply_time"));
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
            sMSMOMessage.setUuid(UUID.randomUUID().toString());
            moList.add(sMSMOMessage);
        } else {
            map.put("code", "-1");
            map.put("code", "error");
        }
        return new SmsHttpMsgResponse(JSON.toJSONString(map));
    }

    @Override
    public String queryReport(String jsonText) {
        return "";
    }

    @Override
    public String queryDeliver(String jsonText) {
        return "";
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        HashMap<String,String> header = Maps.newHashMap();
        header.put("Accept","application/json");
        header.put("Content-Type","application/json;charset=utf-8");

        Map<String,Object> params = Maps.newHashMap();
        params.put("clientid",paramsMaps.get("clientid"));
        params.put("password", DigestUtils.md5Hex(paramsMaps.get("password")));
        String apiUrl = paramsMaps.get("apiUrl") + "/sms-partner/report/"+paramsMaps.get("account")+"/getbalance";
        String param = JSON.toJSONString(params);
        System.out.println("参数：" + param);
        String result =  HttpRequest.sendPostJson(apiUrl , JSON.toJSONString(params), header, 2000);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        if (StringUtils.isNotBlank(result)) {
            JSONObject userInfo = JSON.parseObject(result);
            if (StringUtils.equals(userInfo.getString("code"),"0")) {
                JSONArray array = JSONArray.parseArray(userInfo.getString("data"));
                StringBuffer stringBuffer = new StringBuffer();
                if (array != null && array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject data = array.getJSONObject(i);
                        if (StringUtils.equals(data.getString("product_type"),"0")){
                            stringBuffer = stringBuffer.append("行业余额：").append(data.getString("remain_quantity")).append("条").append(System.getProperty("line.separator"));
                        } else if (StringUtils.equals(data.getString("product_type"),"1")) {
                            stringBuffer = stringBuffer.append("营销余额：").append(data.getString("remain_quantity")).append("条").append(System.getProperty("line.separator"));
                        } else if (StringUtils.equals(data.getString("product_type"),"2")) {
                            stringBuffer = stringBuffer.append("国际余额：").append(data.getString("remain_quantity")).append("元").append(System.getProperty("line.separator"));
                        }
                    }
                }
                return  stringBuffer.toString() ;
            }
        }
        return "余额查询失败";
    }

    public static void main(String[] args)
    {
       String params = "{\"clientid\":\"y00hp3\",\"password\":\"yh123456\",\"smstype\":\"4\",\"apiUrl\":\"http://api.wwwulian.com\",\"account\":\"y00hp3\"}";
        SmsApiYZXCZv1 api = new SmsApiYZXCZv1("ZY",params);
//        String balance = api.balance();
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18268846802");
        message.setId("test123456");
        message.setSmsContent("【惠生活旗舰店】您好！我是店长舒雅，之前在我店里买过东西还记得吧！现在加微信ucc69，就有内部优惠卷及红包领取，活动截止10日");
        api.doSend(message);
//        api.queryReport("");
//        System.out.println(DigestUtils.md5Hex("testmima20120701231212"));
    }

}